package
{
	import flash.xml.XMLDocument;
	import flash.xml.XMLNode;
	import mx.rpc.xml.SimpleXMLEncoder;
	import flash.external.*;
	import flash.utils.ByteArray;
	import flash.net.FileReference;
	
	
	// extends the generic message bean to include an action
	//	<message>
	//		<action>displayperson</action>
	//		<data>Martha</data>
	//		<name>person</name>
	//		<type>action</type>
	//	</message>
	public class ActionMessage
	{
		private const JSFUNCTION:String = "sendActionMessage";
		private const MESSAGETYPE:String = "web_component_messages";
		private var _type:String;
		private var _name:String;
		private var _data:String;		
		private var _action:String;
		
		public function ActionMessage(action:String, name:String, data:String)
		{
			super();
			this.type = MESSAGETYPE;
			this.action = action;
			this.name = name;
			this.data = data;
		}
		
		public function get data():String
		{ 
			return _data;
		}
		
		public function set data(value:String):void
		{
			_data = value;
		}
		
		public function get name():String
		{
			return _name;
		}
		
		public function set name(value:String):void
		{
			_name = value;
		}
		
		public function get type():String
		{
			return _type;
		}
		
		public function set type(value:String):void
		{
			_type = value;
		}
		
		public function get action():String
		{
			return _action;
		}

		public function set action(value:String):void
		{
			_action = value;
		}


		public function toXML():XML
		{
			var qName:QName = new QName("message");
			var xmlDocument:XMLDocument = new XMLDocument();
			var simpleXMLEncoder:SimpleXMLEncoder = new SimpleXMLEncoder(xmlDocument);
			var xmlNode:XMLNode = simpleXMLEncoder.encodeValue(this, qName, xmlDocument);
			var xml:XML = new XML(xmlDocument.toString());
			
			return xml;
		}
		
		// converting message bean to XML string
		public function toXMLString():String
		{		
			var xml:XML = this.toXML();
			return xml.toXMLString();
		}
		
		public function saveXMLBean():void
		{
			//save to local drive
			var ba:ByteArray = new ByteArray();
			ba.writeUTFBytes(this.toXMLString());
			
			var fr:FileReference = new FileReference();
			fr.save(ba, "messagebean.xml");	
		}
		
		// send this message to JavaScript
		public function sendToJS():uint
		{
			var result:uint;
			
			if (ExternalInterface.available) {
				
				result = ExternalInterface.call(JSFUNCTION, MESSAGETYPE, this.toXMLString());
				
			} else {
				trace ("No ExternalInterface available");
			}
			
			return (result);
		}
	}
}